<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow=false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText="searchText"></search-result>
    <!-- 联想建议 -->
    <search-sugges v-else-if="searchText" :searchText="searchText" @search="onSearch"></search-sugges>
    <!-- 历史记录 -->
    <search-history v-else :historyList="historyList" @clear-history="historyList=[]" @search-text="onSearch"></search-history>
  </div>
</template>

<script>
import searchHistory from './components/search-history'
import searchResult from './components/search-result'
import searchSugges from './components/search-sugges'
import { setUser, getUser } from '@/utils/storage'
export default {
  name: 'searchPage',
  data() {
    return {
      searchText: '', // 要搜索的内容
      isResultShow: false, // 搜索结果的显示状态
      historyList: getUser('SEARCH-HISTORY') || [] // 存储搜索记录
    }
  },
  watch: {
    // 一旦搜索历史发生变化就重新存储值
    historyList(val) {
      setUser('SEARCH-HISTORY', val)
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 确认搜索时触发
    onSearch(val) {
      this.searchText = val
      // 判断历史记录中是否存储，如果存在则删除，然后在添加到里面，如果不存在则直接添加
      const index = this.historyList.indexOf(val)
      if (index !== -1) {
        // 存在则删除
        this.historyList.splice(index, 1)
      }
      // 不存在则添加
      this.historyList.unshift(val)
      this.isResultShow = true
    },
    // 点击取消时触发
    onCancel() {
      this.$router.back()
    }
  },
  components: {
    searchHistory,
    searchResult,
    searchSugges
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  /deep/.van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 2;
  }
}
</style>
